package com.pachiraframework.springcloud.user.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.output.XMLOutputter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.aliyun.oss.model.OSSObject;
import com.pachiraframework.springcloud.user.utils.FileUtil;
import com.pachiraframework.springcloud.user.utils.SZSSOUtil;

@RestController
@RequestMapping("/upload")
public class UploadSourceController {
	
	@Value("${images.domain.url}")
    private String IMAGES_DOMAIN_URL;
	
	
	//跳转到上传文件的页面
    @RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
    public ModelAndView goUploadImg() {
        //跳转到 templates 目录下的 uploadimg.html
        return new ModelAndView("uploadimg");
    }

    //处理文件上传
    @RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
    public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        /*System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);*/
        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
        System.out.println(filePath);
        
        
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            // TODO: handle exception
        }
        //返回json
        return "uploadimg success";
    }
	
    
  //处理文件上传
    @RequestMapping(value="/testuploadimg2ali", method = RequestMethod.POST)
    public @ResponseBody String uploadimg2ali(@RequestParam("file") MultipartFile file,
            HttpServletRequest request) throws IOException {
        File multipartToFile = FileUtil.multipartToFile(file);
        SZSSOUtil.uploadFile(multipartToFile, "testpic.jpg");
        System.out.println("文件在阿里云文件服务器路径为："+IMAGES_DOMAIN_URL+"/"+"testpic.jpg");
        //返回json
        return "uploadimg success";
    }
    
    
    
    
    
    
    
    
  //文件上传到阿里云服务器
    /**
     * 一般的上传直接调用这个工程下的已经封装好了的SZSSOUtil中的文件上传方法即可
     */
//    @RequestMapping(value="/upload2ali", method = RequestMethod.POST)
    @RequestMapping(value="/upload2ali", method = RequestMethod.GET)
    public @ResponseBody String upload2aliImg(HttpServletRequest request) {
    	//获取文件路径，生存文件
        String filePath = request.getSession().getServletContext().getRealPath("/");
        filePath = filePath+"user.xml";
        File file = new File(filePath);    	
        String fileName = file.getName();
        
        String fileload = "file";//在阿里的文件服务器上再添加一个文件夹，专门放文件
        
        String destFileName = fileload+"/"+fileName;
		SZSSOUtil.uploadFile(file, destFileName);
        
		System.out.println("文件在阿里云文件服务器路径为："+IMAGES_DOMAIN_URL+"/"+destFileName);
		
		
//        return "uploadimg success";
        return IMAGES_DOMAIN_URL+"/"+destFileName;
    }
	
    @RequestMapping(value="/readimgfromali", method = RequestMethod.GET)
    public void readimgfromali(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        	//跳转到 templates 目录下的 uploadimg.html
            //获取fileid对应的阿里云上的文件对象  
            String fileid = "testpic.jpg";
            OSSObject ossObject = SZSSOUtil.downloadImage(fileid);//bucketName需要自己设置  
         
            // 读去Object内容  返回  
            BufferedInputStream in=new BufferedInputStream(ossObject.getObjectContent());  
            //System.out.println(ossObject.getObjectContent().toString());  
              
              
            BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());  
            //通知浏览器以附件形式下载            
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileid,"utf-8"));  
            //BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\\a.txt")));  
              
            byte[] car=new byte[1024];  
            int L=0;  
            while((L=in.read(car))!=-1){  
                out.write(car, 0,L);  
                  
            }  
            if(out!=null){  
                out.flush();  
                out.close();  
            }  
            if(in!=null){  
                in.close();  
            }  

    }

}
